'use client';

import { useSelector } from 'react-redux';

export function useGlobalStateHook<
  ModuleName extends string,
  RootState extends { [key in string]: any },
  T extends ModuleName,
>(moduleName: T): RootState[T];

// export function useGlobalStateHook<
//   ModuleName extends string,
//   RootState extends {[key in string]: any},
//   T extends ModuleName,
//   U extends undefined // when pass key is undefined , return state of the specified module
// >(moduleName: T, key: U): 'yyy'

export function useGlobalStateHook<
  ModuleName extends string,
  RootState extends { [key in ModuleName]: any },
  T extends ModuleName,
  U extends undefined | keyof RootState[T] = undefined,
>(
  moduleName: T,
  key: U
): U extends keyof RootState[T] ? RootState[T][U] : RootState[T];

export function useGlobalStateHook<
  ModuleName extends string,
  RootState extends { [key in ModuleName]: any },
  T extends ModuleName,
  U extends undefined | keyof RootState[T] = undefined,
>(
  moduleName: T,
  key?: U
): U extends keyof RootState[T] ? RootState[T][U] : RootState[T] {
  // : U extends '' ? RootState[T]: RootState[T][U]
  const curState = useSelector<RootState, RootState[T]>(
    state => state[moduleName]
  );
  if (typeof key === 'undefined') {
    return curState;
  } else if (typeof key === 'string') {
    return curState[key];
  } else {
    return curState[key as unknown as string];
  }
}
